package com.fuyao.cloud.admin.flow.listener;

import com.fuyao.cloud.admin.flow.leave.Leave;
import com.fuyao.cloud.admin.flow.service.org.ILeaveService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component("leaveTaskListener")
public class LeaveTaskListener implements TaskListener {

    @Autowired
    private ILeaveService iLeaveService;
    @Autowired
    private RuntimeService runtimeService;

    /**
     *  完成时修改请假 状态。
     *   eventName->
     *   create: "创建",
     *   assignment: "指派",
     *   complete: "完成",
     *   delete: "删除"
     * @param delegateTask 委托任务对象
     */
    @Override
    public void notify(DelegateTask delegateTask) {
        ProcessInstance processInstance = runtimeService.
                createProcessInstanceQuery()
                .processInstanceId(delegateTask.getProcessInstanceId())
                .singleResult();
        String id = processInstance.getBusinessKey().split(":")[1];
        Leave leave = iLeaveService.getLeaveById(id);
        leave.setStatus(delegateTask.getEventName().equals("complete") ? 2 :1);
        iLeaveService.updateById(leave);
    }
}
